//
//  OrderListView.m
//  car
//
//  Created by chenxu on 15/3/21.
//  Copyright (c) 2015年 chenxu. All rights reserved.
//

#import "OrderListView.h"
#import "NetAPIManager.h"
#import "PrivateMessage.h"
#import "PrivateMessages.h"
#import "BLogin.h"
#define kCellIdentifier_orderList @"Order_Cell"


@interface OrderListView()
@property (nonatomic, strong) NSArray *orders;
@property (nonatomic , copy) OrderSelectBlock selectblock;
@property (nonatomic, strong) UITableView *myTableView;
@property who who;
@property BOOL finished;
@end

@implementation OrderListView

#pragma TabBar
- (void)tabBarItemClicked{
    if (_myTableView.contentOffset.y > 0) {
        [_myTableView setContentOffset:CGPointZero animated:YES];
    }else{
        [self refresh];
    }
}

- (id)initWithFrame:(CGRect)frame Orders:(NSArray *)orders selectblock:(OrderSelectBlock)selectblock Finished:(BOOL)finished who:(who)who{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        _finished = finished;
        _orders = orders;
        _selectblock = selectblock;
        _who = who;
        _myTableView = ({
            UITableView *tableView = [[UITableView alloc] initWithFrame:self.bounds style:UITableViewStylePlain];
            //  tableView.backgroundColor = kColorTableBG;
            tableView.delegate = self;
            tableView.dataSource = self;
            [tableView registerClass:[Order_Cell class] forCellReuseIdentifier:kCellIdentifier_orderList];
            tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
            [self addSubview:tableView];
            tableView;
        });
        
        if (_orders.count > 0) {
            [_myTableView reloadData];
        }else{
            [self sendRequest];
        }
        
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receivemsg:) name:@"newmsg" object:nil];
    }
    return self;
}



/*!
 *  @brief  刷新ui同时异步加载数据
 */
- (void)refreshUI{
    [_myTableView reloadData];
    [self refreshFirst];
}
- (void)refreshToQueryData{
    [self refresh];
}

- (void)refresh{
    [self sendRequest];
}

- (void)refreshFirst{
    if (_orders) {
        [self performSelector:@selector(refresh) withObject:nil afterDelay:0.3];
    }
}

- (void)sendRequest{
    if (_orders.count <= 0) {

    }
    __weak typeof(self) weakSelf = self;
    
    switch (_who) {
        case company:
            //已完成订单
            if (_finished) {
                [[NetAPIManager sharedManager] company_request_finishedorder:[[BLogin curCompany] toCompanyParams] andBlock:^(id data, NSError *error) {
                    // [self endLoading];
                    if (data) {
                        NSMutableArray* orders = [[NSMutableArray alloc]init];
                        NSArray* datalist = [[NSArray alloc]initWithArray:data];
                        for (int i=0; i< [datalist count]; i++) {
                            Order* order = [NSObject objectOfClass:@"Order" fromJSON:[data objectAtIndex:i]];
                            if ([order.Finish boolValue]==true) {
                                [orders addObject:order];
                            }
                        }
                        //存入cars
                        weakSelf.orders = orders;
                        [weakSelf.myTableView reloadData];
                    }
                }];
            }
            //未完成订单
            else{
                [[NetAPIManager sharedManager] company_request_unfinishedorder:[[BLogin curCompany] toCompanyParams] andBlock:^(id data, NSError *error) {
                    // [self endLoading];
                    
                    if (data) {
                        NSMutableArray* orders = [[NSMutableArray alloc]init];
                        NSArray* datalist = [[NSArray alloc]initWithArray:data];
                        
                        for (int i=0; i< [datalist count]; i++) {
                            
                            Order* order = [NSObject objectOfClass:@"Order" fromJSON:[data objectAtIndex:i]];
                            if ([order.Finish boolValue] == false) {
                                [orders addObject:order];
                            }
                            
                            
                        }
                        //存入cars
                        weakSelf.orders = orders;
                        [weakSelf.myTableView reloadData];
                    }
                }];
            }
            break;
         
        case user:
            if (_finished) {
                [[NetAPIManager sharedManager] request_finishedorder:[[Login curLoginUser] toUsernameParams] andBlock:^(id data, NSError *error) {
                    // [self endLoading];
                    if (data) {
                        NSMutableArray* orders = [[NSMutableArray alloc]init];
                        NSArray* datalist = [[NSArray alloc]initWithArray:data];
                        for (int i=0; i< [datalist count]; i++) {
                            Order* order = [NSObject objectOfClass:@"Order" fromJSON:[data objectAtIndex:i]];
                            if ([order.Finish boolValue]==true) {
                                [orders addObject:order];
                            }
                        }
                        //存入cars
                        weakSelf.orders = orders;
                        [weakSelf.myTableView reloadData];
                    }
                }];
            }
            //未完成订单
            else{
                [[NetAPIManager sharedManager] request_unfinishedorder:[[Login curLoginUser] toUsernameParams] andBlock:^(id data, NSError *error) {
                    // [self endLoading];
                    
                    if (data) {
                        NSMutableArray* orders = [[NSMutableArray alloc]init];
                        NSArray* datalist = [[NSArray alloc]initWithArray:data];
                        
                        for (int i=0; i< [datalist count]; i++) {
                            
                            Order* order = [NSObject objectOfClass:@"Order" fromJSON:[data objectAtIndex:i]];
                            if ([order.Finish boolValue] == false) {
                                [orders addObject:order];
                            }
                            
                            
                        }
                        //存入cars
                        weakSelf.orders = orders;
                        [weakSelf.myTableView reloadData];
                    }
                }];
            }
            break;
            
        default:
            break;
    }
   
    
   
}

#pragma mark Table M
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (_orders) {
        return [_orders count];
    }else{
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    Order_Cell *cell = [[[NSBundle mainBundle] loadNibNamed:kCellIdentifier_orderList owner:self options:nil] firstObject];
    
    Order* order = [_orders objectAtIndex:indexPath.row];
    [cell configWithOrder:order];
    
    [cell addBadgeTip:order.badge withCenterPosition:CGPointMake(kScreen_Width-25, [Order_Cell cellHeight]/2)];


    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    //UITableViewCell *cell = [self.myTableView cellForRowAtIndexPath:indexPath];
    //  return cell.contentView.frame.size.height;
    return 103;
}
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    return [ProjectListCell cellHeightWithObj:[_myProjects.list objectAtIndex:indexPath.row]];
//}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (_selectblock) {
        _selectblock([_orders objectAtIndex:indexPath.row]);
    }
}


- (void)receivemsg:(NSNotification*)notify{
    NSDictionary *msg = [notify valueForKey:@"object"];
    NSString *orderid = [msg valueForKey:@"orderid"];
    for (Order* order in _orders) {
        if ([order.Orderid isEqualToString:orderid]) {
            order.badge = [NSString stringWithFormat:@"%d",[order.badge intValue]+1];
        }
      //  NSString* talk = [msg valueForKeyPath:@"Talk"];
     //   PrivateMessage* newmsg = [PrivateMessage privateMessageWithObj:talk andFriend:[Login curLoginUser]];
    }
    [_myTableView reloadData];
}

@end
